import React, { useState, useEffect } from 'react';
import { StyleSheet, View, ScrollView, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { Button, TextInput, ProgressBar, SegmentedButtons } from 'react-native-paper';
import { router } from 'expo-router';
import { useAuth } from '@/contexts/AuthContext';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

export default function BasicInfoScreen() {
  const colorScheme = useColorScheme();
  const { userInfo, userToken, updateProfile } = useAuth();
  const tintColor = Colors[colorScheme ?? 'light'].tint;

  // 表单状态
  const [gender, setGender] = useState(userInfo?.gender || '');
  const [location, setLocation] = useState(userInfo?.location || '');
  const [occupation, setOccupation] = useState(userInfo?.occupation || '');
  const [education, setEducation] = useState(userInfo?.education || '');
  const [bio, setBio] = useState(userInfo?.bio || '');
  const [income, setIncome] = useState(userInfo?.income || '');
  const [isLoading, setIsLoading] = useState(false);

  // 如果用户未登录，重定向到登录页面
  useEffect(() => {
    if (!userToken) {
      router.replace('/auth/login');
    }
  }, [userToken]);

  // 处理表单提交
  const handleSubmit = async () => {
    // 验证必填字段
    if (!gender) {
      Alert.alert('提示', '请选择您的性别');
      return;
    }
    if (!location) {
      Alert.alert('提示', '请填写您的所在地');
      return;
    }
    if (!occupation) {
      Alert.alert('提示', '请填写您的职业');
      return;
    }
    if (!education) {
      Alert.alert('提示', '请选择您的教育程度');
      return;
    }
    if (!income) {
      Alert.alert('提示', '请选择您的收入范围');
      return;
    }

    setIsLoading(true);
    try {
      // 更新用户基本信息
      const success = await updateProfile({
        gender,
        location,
        occupation,
        education,
        bio,
        income
      }, null);

      if (success) {
        // 进入下一步 - 使用setTimeout确保导航在UI更新后执行
        console.log('基本信息更新成功，准备导航到外表特征页面');
        setTimeout(() => {
          console.log('导航到外表特征页面');
          router.push('/profile-setup/appearance');
        }, 500);
      } else {
        Alert.alert('错误', '更新个人资料失败，请重试');
      }
    } catch (error) {
      console.error('Update profile error:', error);
      Alert.alert('错误', '发生未知错误，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <ThemedView style={styles.container}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoidingView}
      >
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <View style={styles.header}>
            <ThemedText style={styles.title}>基本信息</ThemedText>
            <ThemedText style={styles.subtitle}>
              请填写您的基本个人信息，帮助我们更好地了解您
            </ThemedText>
          </View>

          <ProgressBar 
            progress={1/6} 
            color={tintColor} 
            style={styles.progressBar} 
          />

          <View style={styles.formContainer}>
            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>性别</ThemedText>
              <SegmentedButtons
                value={gender}
                onValueChange={setGender}
                buttons={[
                  { value: 'male', label: '男', icon: 'gender-male' },
                  { value: 'female', label: '女', icon: 'gender-female' },
                  { value: 'other', label: '其他', icon: 'gender-non-binary' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>所在城市</ThemedText>
              <View style={styles.pickerContainer}>
                <TextInput
                  value={location}
                  onChangeText={setLocation}
                  mode="outlined"
                  placeholder="例如：北京"
                  style={styles.input}
                  outlineColor="#CCCCCC"
                  activeOutlineColor={tintColor}
                  theme={{ roundness: 10 }}
                  right={<TextInput.Icon icon="map-marker" />}
                />
              </View>
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>职业</ThemedText>
              <TextInput
                value={occupation}
                onChangeText={setOccupation}
                mode="outlined"
                placeholder="例如：软件工程师"
                style={styles.input}
                outlineColor="#CCCCCC"
                activeOutlineColor={tintColor}
                theme={{ roundness: 10 }}
                right={<TextInput.Icon icon="briefcase" />}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>教育程度</ThemedText>
              <SegmentedButtons
                value={education}
                onValueChange={setEducation}
                buttons={[
                  { value: 'high_school', label: '高中' },
                  { value: 'college', label: '大专' },
                  { value: 'bachelor', label: '本科' },
                  { value: 'master', label: '硕士' },
                  { value: 'phd', label: '博士' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>收入范围</ThemedText>
              <SegmentedButtons
                value={income}
                onValueChange={setIncome}
                buttons={[
                  { value: 'low', label: '5万以下' },
                  { value: 'medium', label: '5-15万' },
                  { value: 'high', label: '15-30万' },
                  { value: 'very_high', label: '30万以上' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>个人简介</ThemedText>
              <TextInput
                value={bio}
                onChangeText={setBio}
                mode="outlined"
                placeholder="简单介绍一下自己..."
                multiline
                numberOfLines={4}
                style={styles.textArea}
                outlineColor="#CCCCCC"
                activeOutlineColor={tintColor}
                theme={{ roundness: 10 }}
                right={<TextInput.Icon icon="pencil" />}
              />
            </View>
          </View>

          <View style={styles.buttonContainer}>
            <Button
              mode="contained"
              onPress={handleSubmit}
              style={styles.button}
              labelStyle={styles.buttonText}
              loading={isLoading}
              disabled={isLoading}
              theme={{ roundness: 10 }}
              icon="arrow-right"
            >
              下一步
            </Button>

            <Button
              mode="outlined"
              onPress={() => router.push('/profile-setup')}
              style={[styles.button, styles.backButton]}
              labelStyle={styles.backButtonText}
              theme={{ roundness: 10 }}
              icon="arrow-left"
            >
              返回
            </Button>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    padding: 20,
  },
  header: {
    marginTop: 20,
    marginBottom: 15,
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 5,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 16,
    textAlign: 'center',
    opacity: 0.7,
    marginBottom: 5,
  },
  progressBar: {
    height: 8,
    borderRadius: 4,
    marginBottom: 15,
  },
  formContainer: {
    marginBottom: 20,
  },
  formGroup: {
    marginBottom: 15,
  },
  label: {
    fontSize: 16,
    marginBottom: 8,
    fontWeight: '500',
  },
  input: {
    backgroundColor: 'transparent',
  },
  textArea: {
    backgroundColor: 'transparent',
    height: 100,
  },
  segmentedButtons: {
    marginBottom: 10,
  },
  buttonContainer: {
    marginTop: 'auto',
    marginBottom: 20,
  },
  button: {
    marginBottom: 15,
    paddingVertical: 8,
  },
  buttonText: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  backButton: {
    borderColor: '#ccc',
  },
  backButtonText: {
    fontSize: 16,
  },
  pickerContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
});
